/*
 * 文 件    名:  AdPromotionServiceProviderImpl.java
 * 创建日期:  2012-10-25下午5:23:50
 * 版          权:  Epro Technologies Co., Ltd. Copyright 2011-2012,  All rights reserved
 * 作          者:  tj072
 */
package com.weipu.common.facade.impl;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.AdPromotionServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.model.ActiveModel;
import com.weipu.common.facade.model.BannerModel;
import com.weipu.common.facade.model.CBModel;
import com.weipu.common.facade.model.NewsCornerModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.ProductResultModel;
import com.weipu.common.facade.model.SearchModel;
import com.weipu.common.okhttp.JsonUtils;
import com.weipu.common.okhttp.UrlUtils;
import com.weipu.common.util.CacheUtil;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;

/**
 * @Description 广告服务实现类
 * @version [版本号, 2012-10-25]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 * 
 * @author yw66009
 */
public class AdPromotionServiceProviderImpl extends BaseServiceProviderImpl
		implements AdPromotionServiceProvider {
	private static final String TAG = AdPromotionServiceProviderImpl.class
			.getName();
	// private static Map<String, String> mapUrl;
	//
	// private static Map<String, HttpMethod> mapMethod;

	// 初始化方法名和url键和值存放
	// static
	// {
	// mapUrl = new HashMap<String, String>();
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPAGENEWS,
	// Constant.GETPAGENEWS_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETNEWSINGLE,
	// Constant.GETNEWSINGLE_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPAGEBANNERS,
	// Constant.GETPAGEBANNERS_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPAGEBANNERS_DETAIL,
	// Constant.GETPAGEBANNERS_DETAIL_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETBANNERPRODUCTS,
	// Constant.GETBANNERPRODUCTS_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTBANNERRESUALT,
	// Constant.GETPRODUCTBANNERRESUALT_URL);
	//
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETCATEGORYBANNERS,
	// Constant.GETCATEGORYBANNERS_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETCATEGORYBANNERPRODUCTS,
	// Constant.GETCATEGORYBANNERPRODUCTS_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTSCBRESULT,
	// Constant.GETPRODUCTSCBRESULT_URL);
	// mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETSTARTIMAGE,
	// Constant.GETSTARTIMAGE_URL);
	//
	//
	// }

	// 初始化方法名和httpmetod键和值存放
	// static
	// {
	// mapMethod = new HashMap<String, HttpMethod>();
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPAGENEWS,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETNEWSINGLE,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPAGEBANNERS,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETBANNERPRODUCTS,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTBANNERRESUALT,
	// HttpMethod.GET);
	//
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETCATEGORYBANNERS,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETCATEGORYBANNERPRODUCTS,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTSCBRESULT,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETMESSAGEDAY,
	// HttpMethod.GET);
	// mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_GETSTARTIMAGE,
	// HttpMethod.GET);
	// }

	@Override
	public ArrayList<NewsCornerModel> getPageNews(int index, int pageSize)
			throws DxException {

		// 默认缓存第一页数据
		boolean isEnableLoadFromCache = CacheUtil.getInstance()
				.isEnablePromotionMemCache() && (index <= 1);

		// 开启促销广告缓存
		if (isEnableLoadFromCache) {
			ArrayList<NewsCornerModel> cacheList = GlobalConfig.getInstance()
					.getNewsCache();

			if (null != cacheList && !cacheList.isEmpty()) {
				// 缓存有效
				if (CacheUtil.getInstance().isPromotionHitCache(
						cacheList.get(0))) {
					// //TODO
					// //是否需要一步刷新
					// if(CacheUtil.getInstance().isNeedRefreshCache(cacheList.get(0)))
					// {
					//
					// }
					return new ArrayList<NewsCornerModel>(cacheList);
				}
				// 缓存失效清理数据
				else {
					cacheList.clear();
				}
			}

		}

		ArrayList<NewsCornerModel> listNewsCornerModel = null;
		JSONObject jsonData = requestHttpGetData(Constant.GETPAGENEWS_URL
				+ "?start=" + index + "&take=" + pageSize);
		JSONArray jsonArray = jsonData
				.optJSONArray(ServerConstant.Parameter.CONSTANT_OBJ);
		if (jsonArray != null) {
			listNewsCornerModel = new ArrayList<NewsCornerModel>();
			for (int i = 0; i < jsonArray.length(); i++) {
				listNewsCornerModel.add(NewsCornerModel
						.json2NewsCornerModel(jsonArray.optJSONObject(i)));
			}
		}
		// 开启促销广告缓存，数据不为空
		if (isEnableLoadFromCache
				&& (null != listNewsCornerModel && !listNewsCornerModel
						.isEmpty())) {
			ArrayList<NewsCornerModel> cacheList = GlobalConfig.getInstance()
					.getNewsCache();

			if (null == cacheList) {
				cacheList = new ArrayList<NewsCornerModel>(
						listNewsCornerModel.size());
			} else {
				cacheList.clear();
			}

			// 数据缓存到内存中
			cacheList.addAll(listNewsCornerModel);
		}
		return listNewsCornerModel;
	}

	@Override
	public String getNewSingle(String newID) throws DxException {
		String NewContent = null;
		JSONObject jsonData = requestHttpGetData(Constant.GETNEWSINGLE_URL
				+ "?newID=" + newID);
		JSONObject jsonObj = jsonData
				.optJSONObject(ServerConstant.Parameter.CONSTANT_OBJ);
		if (jsonObj != null) {
			try {
				NewContent = jsonObj
						.getString(ServerConstant.NewsCorner.CONSTANT_NEWCONTENT);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return NewContent;
	}

	@Override
	public ArrayList<BannerModel> getPageBanners(int start, int take,
			String customerId) throws DxException {
		return getPageBanners(start, take, true, customerId);
	}

	@Override
	public ArrayList<BannerModel> getPageBanners(int start, int take,
			boolean isLoadFromCache, String customerId) throws DxException {
		// //允许内存缓存
		// if (isLoadFromCache &&
		// CacheUtil.getInstance().isEnableBannerMemCache())
		// {
		// ArrayList<BannerModel> result =
		// GlobalConfig.getInstance().getBannerCache();
		// if (null != result && !result.isEmpty())
		// {
		// //缓存有效
		// if (CacheUtil.getInstance().isBannerHitCache(result.get(0)))
		// {
		// return result;
		// }
		// else
		// {
		// //缓存失效
		// GlobalConfig.getInstance().getBannerCache().clear();
		// }
		// }
		// }
		//
		// //是否允许本地数据库缓存
		// boolean isEnableLocalDBCache = isLoadFromCache &&
		// CacheUtil.getInstance().isEnableLocaleDBCache();
		// if (isEnableLocalDBCache)
		// {
		// //内存缓存无数据本地数据读取(并刷新缓存)
		// //读取指定栏目下子目录列表
		// ArrayList<BannerModel> localDBCacheList =
		// bannerService.queryAllBanners();
		//
		// //本地有缓存数据
		// if (null != localDBCacheList && !localDBCacheList.isEmpty())
		// {
		// Logger.i(TAG,
		// "getPageBanners.localedb.chache: loading from local, size: " +
		// localDBCacheList.size());
		//
		// //验证缓存数据有效性
		// boolean isCacheHit =
		// CacheUtil.getInstance().isBannerHitCache(localDBCacheList.get(0));
		//
		// //缓存数据有效立即返回
		// if (isCacheHit)
		// {
		// Logger.i(TAG,
		// "getPageBanners.localedb.chache: loading from local success.");
		//
		// //刷新内存缓存(如果开启的话)
		// if (CacheUtil.getInstance().isEnableProductMemCache())
		// {
		// GlobalConfig.getInstance()
		// .getBannerCache()
		// .addAll(new
		// ArrayList<BannerModel>(localDBCacheList));//使用新列表数据存储，防止UI
		// 对列表Clear、remove操作
		// }
		// return localDBCacheList;
		// }
		// //清理缓存
		// else
		// {
		// //清理本地失效缓存数据
		// int topCacheCount = bannerService.clearBanner();
		// Logger.i(TAG,
		// "getPageBanners.localedb.chache: Clear sub product list, size: " +
		// topCacheCount);
		// }
		// }
		// }

		Logger.d(TAG, "Enter into getPageBanners");
		ArrayList<BannerModel> listBannerModel = null;
		JSONObject jsonData = requestHttpGetData(
				UrlUtils.getBannerPageUrl(start, take, customerId));
		JSONArray jsonArray = jsonData
				.optJSONArray(ServerConstant.Parameter.CONSTANT_OBJ);
		listBannerModel = new ArrayList<BannerModel>();
		for (int i = 0; i < jsonArray.length(); i++) {
			listBannerModel.add(BannerModel.json2BannerModel(jsonArray
					.optJSONObject(i)));
		}

		return listBannerModel;
	}

	@Override
	public SearchModel getBannerProductsWhere(String bannerID, int StartIndex,
			int pageCount, String orderByField, double startPrice,
			double endPrice, double beginStar, String currencyCode,long customerID,boolean isFilter,String categoryIds)
			throws DxException { 
		SearchModel searchModel = new SearchModel();
		List<ProductModel> productModels = new ArrayList<ProductModel>();
		// String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + "," +
		// "s>=" + beginStar;
		JSONObject json_data = requestHttpGetData(UrlUtils.getBannerProUrl(
				bannerID, StartIndex, pageCount, orderByField, startPrice,
				endPrice, beginStar,customerID,isFilter,categoryIds), null);
		searchModel
				.setCurrencyCode(json_data
						.optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
		searchModel
				.setCurrencyCodeSymbol(json_data
						.optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
		JSONArray json_products = json_data
				.optJSONArray(ServerConstant.Parameter.CONSTANT_OBJ);
		for (int i = 0; i < json_products.length(); i++) {
			try {
				productModels.add(ProductModel.json2product(json_products
						.getJSONObject(i)));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		searchModel.setProductModels(productModels);
		return searchModel;
	}

	/**
	 * 根据分类推广ID获取产品数量以及星级数量
	 */
	@Override
	public ProductResultModel GetProductBannerResualt(String bannerID,
			double startPrice, double endPrice, double beginStar,long customerID,boolean isFilter,String categoryIds)
			throws DxException {
		ProductResultModel productResultModel = new ProductResultModel();
		// getOrDeleteAuthenticationAndsetHeadAndmessage(null);
		// ResponseEntity<String> responseEntity;
		String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
				+ "s>=" + beginStar;
		JSONObject json_data = requestHttpGetData(
				Constant.GETPRODUCTBANNERRESUALT_URL + "?bannerID=" + bannerID
						+ "&whereStr=" + whereStr+"&CustomerID="+customerID+"&IsFilter="+isFilter+"&categoryIds="+categoryIds, null);
		JSONObject json_products = json_data
				.optJSONObject(Constant.JSON_PRODUCTS);
		productResultModel = ProductResultModel.json2product(json_products);
		return productResultModel;
	}

	@Override
	public ArrayList<CBModel> getCategoryBanners(int categoryID)
			throws DxException {
		ArrayList<CBModel> listCBModel = null;
		// getOrDeleteAuthenticationAndsetHeadAndmessage(null);
		// ResponseEntity<String> responseEntity;
		JSONObject jsonData = requestHttpGetData(Constant.GETCATEGORYBANNERS_URL
				+ "?categoryID=" + categoryID);
		JSONArray jsonArray = jsonData
				.optJSONArray(ServerConstant.Parameter.CONSTANT_OBJ);
		if (jsonArray != null) {
			listCBModel = new ArrayList<CBModel>();
			for (int i = 0; i < jsonArray.length(); i++) {
				listCBModel
						.add(CBModel.json2CBModel(jsonArray.optJSONObject(i)));
			}
		}
		return listCBModel;
	}

	@Override
	public ArrayList<ProductModel> getCategoryBannerProductsWhere(String cbID,
			int StartIndex, int pageCount, String orderbyField,
			double startPrice, double endPrice, double beginStar)
			throws DxException {
		ArrayList<ProductModel> listProductModel = null;
		String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
				+ "s>=" + beginStar;
		JSONObject jsonData = requestHttpGetData(
				Constant.GETCATEGORYBANNERPRODUCTS_URL + "?cbID=" + cbID
						+ "&StartIndex=" + StartIndex + "&pageCount="
						+ pageCount + "&orderbyField="  +"{"+orderbyField+"}"
						+ "&whereStr=" + whereStr, null);
		JSONArray jsonArray = jsonData
				.optJSONArray(ServerConstant.Parameter.CONSTANT_OBJ);
		if (jsonArray != null) {
			listProductModel = new ArrayList<ProductModel>();
			for (int i = 0; i < jsonArray.length(); i++) {
				listProductModel.add(ProductModel.json2product(jsonArray
						.optJSONObject(i)));
			}
		}
		return listProductModel;
	}

	/**
	 * 根据分类推广ID获取产品数量以及星级数量
	 */
	@Override
	public ProductResultModel GetProductsCBResult(String cbID,
			double startPrice, double endPrice, double beginStar)
			throws DxException {
		ProductResultModel productResultModel = new ProductResultModel();
		String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
				+ "s>=" + beginStar;

		JSONObject json_data = requestHttpGetData(Constant.GETPRODUCTSCBRESULT_URL
				+ "?cbID=" + cbID + "&whereStr=" + whereStr, null);
		JSONObject json_products = json_data
				.optJSONObject(Constant.JSON_PRODUCTS);
		productResultModel = ProductResultModel.json2product(json_products);

		return productResultModel;
	}

	@Override
	public String getMessageDay() throws DxException {
		// //允许每日消息缓存
		// if (CacheUtil.getInstance().isEnableMessageDayMemCache())
		// {
		// String msg = GlobalConfig.getInstance().getMessageOfDayCache();
		// if (!TextUtils.isEmpty(msg))
		// {
		// return msg;
		// }
		// }
		//
		// String result = null;
		// getOrDeleteAuthenticationAndsetHeadAndmessage(null);
		// ResponseEntity<String> responseEntity;
		// JSONObject jsonObj = null;
		// String messageContent = null;
		// try
		// {
		// Logger.i("getMessageDay", "star");
		// oldTime = System.currentTimeMillis();
		// responseEntity =
		// restTemplate.exchange(mapUrl.get(ServerConstant.RequestMethodNameConstant.METHOD_GETMESSAGEDAY),
		// mapMethod.get(ServerConstant.RequestMethodNameConstant.METHOD_GETMESSAGEDAY),
		// requestEntity,
		// String.class);
		// nowTime = System.currentTimeMillis();
		// MyTrafficStat.getNetSpeed(ServerConstant.RequestMethodNameConstant.METHOD_GETMESSAGEDAY,
		// oldTime, nowTime);
		// MyTrafficStat.getRxbytes(ServerConstant.RequestMethodNameConstant.METHOD_GETMESSAGEDAY);
		// Logger.i("getMessageDay", "end");
		// result = responseEntity.getBody().toString();
		// JSONObject json = returnResult(result);
		// JSONObject jsonData = json.optJSONObject(Constant.JSON_DATA);
		// jsonObj =
		// jsonData.optJSONObject(ServerConstant.Parameter.CONSTANT_OBJ);
		// messageContent =
		// jsonObj.optString(ServerConstant.Parameter.CONSTANT_MESSAGECONTENT);
		// Logger.d("---", "--" + messageContent);
		// }
		// catch (HttpClientErrorException e)
		// {
		// throw new
		// DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
		// }
		// catch (ResourceAccessException e)
		// {
		// Logger.e(e.getMessage(), e);
		// //链接超时
		// if (e.getCause() instanceof SocketTimeoutException||e.getCause()
		// instanceof ConnectTimeoutException)
		// {
		// throw new
		// DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT);
		// }
		// else if(e.getCause() instanceof UnknownHostException){
		// throw new
		// DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
		// }
		// else
		// {
		// if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){
		// throw new
		// DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
		// }else{
		// throw new
		// DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
		// }
		// }
		// }catch(HttpServerErrorException e){
		// throw new
		// DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR);
		// }
		// //允许每日消息缓存
		// if (CacheUtil.getInstance().isEnableMessageDayMemCache())
		// {
		// GlobalConfig.getInstance().setMessageOfDayCache(messageContent);
		// }
		//
		// String[] key = {"messageOfDay", "refreshTime"};
		// HashMap<String, String> messageConfig =
		// StringUtil.getConfig(DXApplication.getContext(), key);
		// messageConfig.put("messageOfDay", messageContent);
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// String currentTime = sdf.format(new Date());
		// messageConfig.put("messageOfDay", currentTime);
		// StringUtil.saveConfig(DXApplication.getContext().getApplicationContext(),
		// messageConfig);
		//
		// return messageContent;
		return null;
	}

	@Override
	public String[] GetStartImage(int width, int height, String lanuage)
			throws DxException {
		JSONObject jsonData = requestHttpGetData(Constant.GETSTARTIMAGE_URL
				+ "?width=" + width + "&height=" + height + "&language="
				+ lanuage);
		// 小图地址数组
		JSONArray PicArray = jsonData.optJSONArray("Imgs");
		String[] Urls = null;
		if (null != PicArray && PicArray.length() > 0) {
			int len = PicArray.length();
			Urls = new String[len];
			for (int i = 0; i < len; i++) {
				String tmpUrl = "";
				try {
					tmpUrl = PicArray.getString(i);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (null != tmpUrl && tmpUrl.length() > 0) {
					Urls[i] = tmpUrl;
				}
			}
		}
		return Urls;
	}

	@Override
	public BannerModel getBannerDetail(String bannerId, String cicid)
			throws DxException {
		Logger.d(TAG, "Enter into getPageBanners");
		BannerModel bannerModel = null;
		JSONObject jsonData = requestHttpGetData(
				UrlUtils.getBannerDetailUrl(bannerId, cicid));
		JSONObject objData = jsonData
				.optJSONObject(ServerConstant.Parameter.CONSTANT_OBJ);
		bannerModel = BannerModel.json2BannerModel(objData);
		return bannerModel;
	}

	@Override
	public ActiveModel GetActiveInfor(int getType, String dataID) throws DxException {
		JSONObject requestHttpGetData = requestHttpGetData(Constant.GETACTIVEINFOR_URL+"?getType="+getType+"&dataID="+dataID);
		return JsonUtils.fromJson(requestHttpGetData.toString(), ActiveModel.class);
	}

}
